﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using bts_webapp.Models;

namespace bts_webapp
{
    public partial class UserPermission : System.Web.UI.Page
    {
        public void combo_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            if (this.combo.SelectedValue == "Nhân viên tổ ViBa")
            {
                this.RadGrid1.Visible = true;
                this.RadGrid1.Rebind();
            }
            else
            {
                this.RadGrid1.Visible = false;
            }
        }

        public string UserId
        {
            get
            {
                return this.Request.Params["uid"];
            }
        }
        
        public void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            // TODO: Implement this method
            this.RadGrid1.DataSource = this.GetData();
        }

        public void RadGrid1_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
        {
            // TODO: Implement this method
            if (e.Item is GridDataItem)
            {
                var dataItem = e.Item as GridDataItem;
                var rowView = dataItem.DataItem as DataRowView;
                var cbActive = (CheckBox)dataItem["IsActive"].FindControl("cbActive");
                cbActive.Checked = (bool)rowView["IsActive"];
                var cbEdit = (CheckBox)dataItem["IsEdit"].FindControl("cbEdit");
                cbEdit.Checked = (bool)rowView["IsEdit"];
            }
        }

        public void btSubmit_Click(object sender, EventArgs e)
        {
            var context = new BTSModelDataContext();
            if (this.combo.SelectedValue == "User1")
            {
                
                //delete all items in 
                var deletedItems = context.VIBA_QUYENs.Where(x => x.User_Id == this.UserId);
                if (deletedItems.Count() > 0)
                {
                    context.VIBA_QUYENs.DeleteAllOnSubmit(deletedItems);
                    context.SubmitChanges();
                }
                //re-insert
                bool hasItem = false;
                foreach (var item in this.RadGrid1.MasterTableView.Items)
                {
                    if (item is GridDataItem)
                    {
                        
                        var dataItem = item as GridDataItem;
                        var checkActive = (CheckBox)dataItem["IsActive"].FindControl("cbActive");
                        var checkEdit = (CheckBox)dataItem["IsEdit"].FindControl("cbEdit");
                        if (checkActive.Checked)
                        {
                            var r = new VIBA_QUYEN()
                            {
                                User_Id = this.UserId,
                                User_Email = string.Empty,
                                Page = dataItem["Page"].Text,
                                Action = checkEdit.Checked ? "Edit": "ReadOnly"
                            };
                            context.VIBA_QUYENs.InsertOnSubmit(r);
                            hasItem = true;
                        }
                    }
                }
                if (hasItem)
                    context.SubmitChanges();
                //update to table Users
                var user = context.VIBA_Users.FirstOrDefault(x => x.User_Id == this.UserId);
                if (user != null)
                {
                    user.User_Role = 1;
                    context.SubmitChanges();
                }
            }
            else if (this.combo.SelectedValue == "Admin")
            {
                //update to table Users
                var user = context.VIBA_Users.FirstOrDefault(x => x.User_Id == this.UserId);
                if (user != null)
                {
                    user.User_Role = 0;
                    context.SubmitChanges();
                }
            }
            else
            {
                //update to table Users
                var user = context.VIBA_Users.FirstOrDefault(x => x.User_Id == this.UserId);
                if (user != null)
                {
                    user.User_Role = 2;
                    context.SubmitChanges();
                }
            }

            //register client script
            var script = "CloseWindow();";
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), Guid.NewGuid().ToString(), script, true);
        }

        public void list_SelectedIndexChanged(object sender, EventArgs e)
        {
            // TODO: Implement this method
            //if (this.list.SelectedValue == "Nhân viên tổ ViBa")
            //{
            //    this.RadGrid1.Visible = true;
            //    this.RadGrid1.Rebind();
            //}
            //else
            //{
            //    this.RadGrid1.Visible = false;
            //}
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            //
            if (this.IsPostBack)
            {
                
                return;
            }
            
            var ctx = new Models.BTSModelDataContext();
            var user = ctx.VIBA_Users.FirstOrDefault(x => x.User_Id == this.UserId);
            if (user != null)
            {
                if (user.User_Role == 0)//admin
                {
                    this.combo.SelectedIndex = 0;
                    this.RadGrid1.Visible = false;
                }
                else if (user.User_Role == 1)
                {
                    
                    //get permission 
                    this.combo.SelectedIndex = 1;
                    this.RadGrid1.Visible = true;
                }
                else
                {
                    this.combo.SelectedIndex = 2;
                    this.RadGrid1.Visible = false;
                }
            }
        }

        private DataTable GetData() 
        {
            var ctx = new Models.BTSModelDataContext();
           
            var data = new DataTable("tb");
            data.Columns.Add("Page", typeof(string));
            data.Columns.Add("PageDescription", typeof(string));
            data.Columns.Add("IsActive", typeof(bool));
            data.Columns.Add("IsEdit", typeof(bool));
            var pages = ctx.VIBA_Pages.ToList();
            var permissions = ctx.VIBA_QUYENs.Where(x => x.User_Id == this.UserId).ToList();
            for (int i = 0; i < pages.Count; i++)
            {
                var row = data.NewRow();
                row.ItemArray = new object[] { pages[i].Page, pages[i].PageDescription, permissions.Exists(x => x.Page == pages[i].Page), permissions.Exists(x => x.Action.ToLower() == "edit" && x.Page == pages[i].Page) };
                data.Rows.Add(row);
            }

            return data;
        }

        public class TempPermission
        {
            public string Page { get; set; }
            public string PageDescription { get; set; }
            public bool IsActive { get; set; }
            public bool IsEdit { get; set; }
        }
    }
}